$(document).ready(function ($) {
    user = {};
    Store.getUser().then(function (data) {
        if (data != null) {
            user = data;
        }
    });

    var pro_count = $(".pro-count");
    var time = null;
    pro_count.keyup(function () {
        var _this = $(this);
        var i = _this.val();
        var norm = /^[0-9]*$/;
        if (_this.val() == "") {
            _this.val(1)
        }
        if (_this.val() < 0) {
            _this.val(0);
        }
        if (_this.val() > 5) {
            _this.val(5)
        }
        updataTable(_this);
    })

    pro_count.hover(function () {
        pro_count.mouseup(function () {
            updataTable($(this));
        })
    })

    updataTable = function (data) {
        var _this = $(data);
        _this.attr("disabled",true);
        $.ajax({
            url:Store.context +"/car/add2cart.do",
            type:"post",
            data:{
                pid: _this.attr("id"),
                count:_this.val(),
            },
            success:function (td) {
                updatasubtotal(_this);
            }
        })
    }


    updatasubtotal = function (data) {
        var _this = $(data);
        var count = _this.val();
        var shelfprice = getShelfPrice(_this);
        var subtotal = getOldPrice(_this);
        var oldprice = subtotal.html();
        var newprice = shelfprice * count;
        newprice = newprice.toFixed(1);
        subtotal.html(newprice);

        var diffrent = newprice - oldprice;
        updataTotal(diffrent);
        _this.attr("disabled",false);
    }

    updataTotal = function (diff) {
        var total = $("#total").html();
        total = parseFloat(total, 10);
        var newTotal = total + diff;
        newTotal = newTotal.toFixed(1);
        $("#total").html(newTotal);
        $("#after-total").html(newTotal);
    }

    deletesingle = function (data,pid) {
        var _this = $(data);
        $.ajax({
            url:Store.context + "/car/deletesingle.do",
            type:'post',
            data:{
                uid : user.uid,
                pid : pid
            },
            success:function (data) {
                if(data.status == '0'){
                    _this.parent().parent().remove();
                }
            }
        })
    }

    deleteAll = function () {
        $.ajax({
            url:Store.context + "/car/deletecar.do",
            type:"post",
            success:function (d) {
                if(d){
                    location.reload();
                }
            }
        })
    }


    function getOldPrice(data) {
        return $(data).parent().parent().next().children("span");
    }
    function getShelfPrice(data) {
        return $(data).parent().parent().prev().children().html();
    }
},(jQuery));